<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\system;


use app\admin\model\SystemSign;
use app\admin\model\SystemRegion;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="签到管理")
 */
class Sign extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemSign();
        $this->region = new SystemRegion();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $district = $this->region->where(['level'=>'区县'])->select()->toArray();
        $town = $this->region->where(['level'=>'乡镇'])->select()->toArray();
        $community = $this->region->where(['level'=>'社区'])->select()->toArray();
        $this->assign('district', $district);
        $this->assign('town', $town);
        $this->assign('community', $community);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $district = $this->region->where(['level'=>'区县'])->select()->toArray();
        $town = $this->region->where(['level'=>'乡镇'])->select()->toArray();
        $community = $this->region->where(['level'=>'社区'])->select()->toArray();
        $this->assign('district', $district);
        $this->assign('town', $town);
        $this->assign('community', $community);
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="补签")
     */
    public function selfSign($id)
    {
        $info = $this->model->find($id)->toArray();
        $signin = $this->model->where(['type'=>'签到','uid'=>$info['uid']])->count();
        $signout = $this->model->where(['type'=>'签退','uid'=>$info['uid']])->count();
        if($signout >= $signin){
            $this->error('已签退无需补签');
        }
        $save = $this->model->save(
            [
                'uid'=>$info['uid'],
                'district'=>$info['district'],
                'town'=>$info['town'],
                'type'=>'签退',
                'community'=>$info['community'],
                'content'=>'补签',
                'image'=> $info['image'],
                'sign_date'=>$info['sign_date'],
                'create_time'=>$info['create_time'],
                'update_time'=>$info['update_time']
            ]
        );
        if($save) {
            $this->success('补签成功');
        }
    }
    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        if ($this->request->isPost()) {
            try {
                $file = $this->request->file('file');
            } catch (\Exception $e) {
                return '<script type="text/javascript">
                        alert("请上传文件")
                        history.go(-1)
                    </script>';
            }
            $ext = $file->getOriginalExtension();
            if(!in_array( $ext, ['xlsx'])){
                return '<script type="text/javascript">
                        alert("请上传xlsx文件")
                        history.go(-1)
                    </script>';
            }
            $savename = \think\facade\Filesystem::disk('public')->putFile( 'upload', $file);
            $path = rtrim(__FILE__,'app\admin\controller\system\Sign.php').'\public\\'.str_replace( '/','\\',$savename);
//            $path = rtrim(__FILE__,'app/admin/controller/system/Sign.php').'/public/'.$savename;
            //var_dump($path);die;
            $excel = IOFactory::load($path);
            $sheet = $excel->getSheet(0)->toArray();
            array_shift($sheet);  //删除第一个数组(标题);
            $data = [];
            foreach ($sheet as $k => $v) {
                $data[$k]['district']=$v[1];
                $data[$k]['town']=$v[2];
                $data[$k]['community']=$v[3];
                $data[$k]['content']=$v[4];
                $data[$k]['image']=$v[5];
                $data[$k]['sign_date']=$v[6];
                $data[$k]['create_time']=$v[7];
                $data[$k]['update_time']=$v[7];
                $data[$k]['type']=$v[8];
                $data[$k]['uid']=$v[9];
                $data[$k]['party']=$v[10];
            }
            $save = $this->model->saveAll($data);
            if($save){
                return '<script type="text/javascript">
                        alert("导入成功")
                        parent.location.reload();
                    </script>';
            }
        }
       return  $this->fetch();
    }

    public function getOptions($name)
    {
        $parent = $this->region->where(['name'=>$name])->find()->toArray();
        $list = $this->region->where(['pid'=>$parent['id']])->select()->toArray();
        $data = [];
        foreach ($list as $key=>$value){
            $data[$key]['id']=$value['id'];
            $data[$key]['name']=$value['name'];
        }
        $data = [
            'code'  => 0,
            'msg'   => '',
            'data'  => $data,
        ];
        return json($data);
    }
}